package com.atguigu.sparsearray;

/**
 * 稀疏数组
 *
 * @author dataexa
 * @Date 2023/11/14
 */
public class SparseArray {
    public static void main(String[] args) {
        // 创建原始的二维数组
        int[][] arr = new int[4][6];
        arr[1][2] = 1;
        arr[2][1] = 2;
        arr[1][3] = 1;
        arr[3][3] = 2;
        // 输出原始的二维数组
        System.out.println("原始的数据:");
        printDoubleArray(arr);
        // 二维数组------稀疏数组
        // 1. 先获取所有非0的数量
        int sum = 0;
        for (int[] ints : arr) {
            for (int anInt : ints) {
                if (anInt != 0) {
                    sum++;
                }
            }
        }
        int[][] sapre = new int[sum + 1][3];
        sapre[0][0] = arr.length;
        sapre[0][1] = arr[0].length;
        sapre[0][2] = sum;
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int i1 = 0; i1 < arr[0].length; i1++) {
                if (arr[i][i1] != 0) {
                    count++;
                    sapre[count][0] = i;
                    sapre[count][1] = i1;
                    sapre[count][2] = arr[i][i1];
                }
            }
        }
        System.out.println("二维数组------稀疏数组:");
        printDoubleArray(sapre);

        // 稀疏数组------二维数组
        int[][] newArray = new int[sapre[0][0]][sapre[0][1]];
        for (int i = 1; i < sapre.length; i++) {
            newArray[sapre[i][0]][sapre[i][1]] = sapre[i][2];
        }
        System.out.println("稀疏数组------二维数组:");
        printDoubleArray(newArray);
    }

    private static void printDoubleArray(int[][] arr) {
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }
    }
}
